﻿using Dm.util;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YJ_App.Tool.Log;
using YJ_App.Tool.Message;
using YJ_Code.Entities.Topic;
using YJ_Code.Entities.User;
using YJ_Code.Enums;
using YJ_Code.Tool;
using YJ_Core.Entities.Common;
using YJ_Core.Entities.Utils;
using YJ_Core.Tool.Token;
using static YJ_App.Admin_System.Dtos.TopicAdminDto;
using static YJ_App.Tool.Message.MessageDto;

namespace YJ_App.Admin_System.Service
{
    /// <summary>
    /// 登录服务
    /// </summary>
    [ApiDescriptionSettings(ApiGroupEnumsCode.TopicAdmin, Name = "TopicAdmin")]
    public class TopicAdminService : IDynamicApiController, ITransient
    {
        /// <summary>
        /// sql
        /// </summary>
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 站内消息
        /// </summary>
        private readonly IMessageService _messageService;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogService _logService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        public TopicAdminService(ISqlSugarClient db, IMessageService messageService, ILogService logService)
        {
            _db = db;
            _messageService = messageService;
            _logService = logService;
        }

        /// <summary>
        /// 话题列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SelectTopicListResp> SelectTopicList(SelectTopicListInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            //去掉入参前后空格
            ToolHelper.TrimStrings(input);
            RefAsync<int> total = 0;

            var list = await _db.Queryable<Topics>()
                .WhereIF(!string.IsNullOrWhiteSpace(input.Content), (t1) => t1.Content.Contains(input.Content))
                .WhereIF(input.CheckStatus.HasValue, (t1) => t1.CheckStatus == input.CheckStatus)
                 .WhereIF(input.StartDate.HasValue && input.EndDate.HasValue,
                (t1) => t1.CreateTime >= input.StartDate && t1.CreateTime < input.EndDate)
                .WhereIF(!string.IsNullOrWhiteSpace(input.KeyWord), (t1) =>
                t1.Title.Contains(input.KeyWord)
                || t1.UserId.Contains(input.KeyWord)
                || t1.CreateMan.Contains(input.KeyWord))
                .Select((t1) => new SelectTopicListOutput
                {
                    Title = t1.Title,
                    UserId = t1.UserId,
                    Status = t1.Status,
                    Content = t1.Content,
                    Address = t1.Address,
                    TopicId = t1.TopicId,
                    Latitude = t1.Latitude,
                    Longitude = t1.Longitude,
                    CreateMan = t1.CreateMan,
                    CreateTime = t1.CreateTime,
                    CheckStatus = t1.CheckStatus,
                    LocationName = t1.LocationName,
                    CollectCount = t1.CollectCount,
                    LikeCount = t1.LikeCount,
                    ShareCount = t1.ShareCount,
                    SkimThroughCount = t1.SkimThroughCount,
                })
                .OrderByDescending(t => t.CreateTime)
                .ToPageListAsync(input.Page, input.PageSize, total);

            // 获取图片
            var images = await _db.Queryable<Images>()
                .Where(it => list.Select(it => it.TopicId).Contains(it.Code)).ToListAsync();

            var userInfo = await _db.Queryable<UserInfo>()
                .Where(it => list.Select(it => it.UserId).Contains(it.UserId)).ToListAsync();

            foreach (var item in list)
            {
                item.Images = images.Where(it => it.Code == item.TopicId).Select(it => it.Url).ToList();
                item.Email = userInfo.FirstOrDefault(it => it.UserId == item.UserId).Email ?? "";
            }

            return new SelectTopicListResp { List = list, Total = total, Message = "OK", StatusCode = 200 };
        }

        /// <summary>
        /// 审核话题
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseStatus> CheckTopic(CheckTopicInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            //去掉入参前后空格
            ToolHelper.TrimStrings(input);

            if (!input.CheckStatus.HasValue)
            {
                throw Oops.Bah("请选择审核状态");
            }

            var topic = await _db.Queryable<Topics>()
                .FirstAsync(it => it.TopicId == input.TopicId) ?? throw Oops.Bah("话题信息异常");

            if (input.CheckStatus.HasValue && input.CheckStatus.Value == 2)
            {
                if (string.IsNullOrWhiteSpace(input.RejectReason))
                {
                    throw Oops.Bah("审核驳回，请说明理由【2】");
                }
                topic.RejectReason = input.RejectReason;

                // 创建站内消息
                await _messageService.CreateMessage(new CreateMessageInput
                {
                    MsgType = 1,
                    Title = "话题审核不通过",
                    Content = input.RejectReason,
                    UserId = input.UserId,
                    TopicId = input.TopicId,
                });
            }

            topic.CheckStatus = input.CheckStatus.Value;
            topic.CheckMan = user.UserName;
            topic.CheckTime = DateTime.Now;

            try
            {
                int count = await _db.Updateable(topic)
                    .WhereColumns(it => it.TopicId)
                    .UpdateColumns(it => new
                    {
                        it.CheckStatus,
                        it.RejectReason,
                        it.CheckMan,
                        it.CheckTime
                    }).ExecuteCommandAsync();
                if (count < 1)
                {
                    throw Oops.Bah("审核异常【Updateable】");
                }
            }
            catch (Exception ex)
            {

                throw Oops.Bah($"审核接口异常【CheckTopic】", ex);
            }

            string message = string.Empty;
            if (topic.CheckStatus == 1)
            {
                message = "审核通过";
            }
            else if (topic.CheckStatus == 2)
            {
                message = "已驳回，审核不通过";
            }
            else
            {
                message = "";
            }

            // 发布日志
            await _logService.AddLog(new LogDto.AddLogInput
            {
                TopicId = topic.TopicId,
                Type = message,
                UserName = user.UserName,
                Content = input.RejectReason ?? "系统审核通过"
            });

            return new ResponseStatus { Message = message, StatusCode = 200 };
        }

        /// <summary>
        /// 获取话题详情
        /// </summary>
        /// <returns></returns>
        public async Task<SelectTopicDetailResp> SelectTopicDetail(SelectTopicDetailInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            //去掉入参前后空格
            ToolHelper.TrimStrings(input);

            var topic = await _db.Queryable<Topics>()
                .FirstAsync(it => it.TopicId == input.TopicId) ?? throw Oops.Bah("信息有误");

            var images = await _db.Queryable<Images>()
                .Where(it => it.Code == topic.TopicId).ToListAsync();

            var output = new SelectTopicDetailOutput
            {
                TopicId = topic.TopicId,
                Address = topic.Address,
                CheckMan = topic.CheckMan,
                CheckStatus = topic.CheckStatus,
                CheckTime = topic.CheckTime,
                Content = topic.Content,
                CreateMan = topic.CreateMan,
                CreateTime = topic.CreateTime,
                Latitude = topic.Latitude,
                LikeCount = topic.LikeCount,
                LocationName = topic.LocationName,
                Longitude = topic.Longitude,
                RejectReason = topic.RejectReason,
                Status = topic.Status,
                Title = topic.Title,
                UserId = topic.UserId,
                Email = topic.Email,
                Images = images.Select(it => it.Url).ToList(),
            };

            var logs = await _db.Queryable<LogRecord>()
                .Where(it => it.TopicId == topic.TopicId).ToListAsync();

            return new SelectTopicDetailResp
            {
                Message = "获取成功",
                StatusCode = 200,
                TopicDetail = output,
                LogDetail = logs
            };
        }
    }
}
